const BaseService = require('./base')
const { Op } = require('sequelize')
class CategoricalService extends BaseService {
	constructor(...args) {
		super(...args)
		this.modelName = 'Categorical'
	}

	async del(ids) {
		if (!Array.isArray(ids)) ids = [ids]
		let transaction

		try {
			// 建立事务对象
			transaction = await this.ctx.model.transaction()
			for (let i = 0; i < ids.length; i++) {
				const id = ids[i]
				// 判断是否存在关联数据 存在则不能删除
				let findRecord = await this.ctx.model.Artical.findOne({
					where: {
						category_id: {
							[Op.eq]: id,
						},
					},
				})

				if (findRecord) {
					throw error //数据存在关联
				}
				let res = await this.ctx.model[this.modelName].destroy({
					where: {
						id: {
							[Op.eq]: id,
						},
					},
					transaction,
				})
				if (!res) {
					throw error //数据不存在就回滚
				}
			}
			// 提交事务
			await transaction.commit()
			return { flag: true }
		} catch (error) {
			// 事务回滚
			await transaction.rollback()
			return { flag: false, msg: '数据存在关联', code: 400 }
		}
	}
	async updateList(arr) {
		let count = 0
		for (let i = 0; i < arr.length; i++) {
			let user = arr[i]
			const u = await this.ctx.model[this.modelName].findOne({
				where: {
					name: {
						[Op.eq]: user.name,
					},
				},
			})
			// 没找到了数据证明不存在相同信息
			if (!u) {
				// 创建用户
				let res = await this.ctx.model[this.modelName].create({
					...user,
				})
				if (res) count++
			} else {
				// 找到了数据证明存在，不能进行添加
				continue
			}
		}
		return { flag: true, count }
	}
}

module.exports = CategoricalService
